<template>
    <div
        class="mptransrecordqry"
        v-loading="pageLoading"
        element-loading-background="rgba(255, 255, 255, 0.7)"
    >
        <cardComponent pageTitle="分期付款申请记录查询">
            <template slot="cardBody">
                <!-- 搜索表单模块 -->
                <el-form
                    class="searchForm"
                    ref="searchForm"
                    :model="searchForm"
                    :rules="rules"
                    :inline="true"
                    label-position="right"
                    size="small"
                    label-width="100px"
                >
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="账户类别:" class="text_fl">
                                <el-select
                                    v-model="searchForm.accttype"
                                    placeholder="请选择账户类别"
                                    clearable
                                    @change="changeCardList"
                                >
                                    <el-option
                                        v-for="item in AccountionTYPE_INFO"
                                        :label="item.label"
                                        :value="item.code"
                                        :key="item.label"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="卡号:" class="text_fl">
                                <el-select
                                    v-model="searchForm.cardno"
                                    placeholder="请选择卡号"
                                    clearable
                                >
                                    <el-option
                                        v-for="item in cardList"
                                        :label="item.CARDNBR"
                                        :value="item.CARDNBR"
                                        :key="item.CARDNBR"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="分期类型:" label-position="left" prop="mpType">
                                <el-select placeholder="请选择" v-model="searchForm.mpType" clearable>
                                    <el-option
                                        v-for="(item, index) in mptypeList"
                                        :key="index"
                                        :label="item.label"
                                        :value="item.code"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="分期状态:" label-position="left" prop="status">
                                <el-select placeholder="请选择" v-model="searchForm.status" clearable>
                                    <el-option
                                        v-for="(item, index) in mpappstatusList"
                                        :key="index"
                                        :label="item.label"
                                        :value="item.code"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-button
                                type="primary"
                                size="small"
                                icon="el-icon-search"
                                @click="handleGetListData('first')"
                            >查 询</el-button>
                            <el-button
                                type="primary"
                                size="small"
                                icon="el-icon-refresh-right"
                                @click="handleReset"
                            >重 置</el-button>
                        </el-col>
                    </el-row>
                </el-form>

                <!-- 表格数据展示模块 -->

                <el-table
                    :data="tableData"
                    border
                    stripe
                    @row-click="handleSelectRow"
                    header-row-class-name="headerRow"
                    ref="showListTable"
                    class="heard-bg business_table"
                >
                    <el-table-column label="分期付款申请编号" min-width="120">
                        >
                        <template slot-scope="scope">{{scope.row.APPREF}}</template>
                    </el-table-column>
                    <el-table-column label="申请录入日期">
                        <template slot-scope="scope">{{scope.row.INPDATE}}</template>
                    </el-table-column>
                    <el-table-column label="商品编号">
                        <template slot-scope="scope">{{scope.row.PRPRDID}}</template>
                    </el-table-column>
                    <el-table-column label="商品名称">
                        <template slot-scope="scope">{{scope.row.PRONAME}}</template>
                    </el-table-column>
                    <el-table-column label="商品金额">
                        <template slot-scope="scope">{{scope.row.MPAMT}}</template>
                    </el-table-column>
                    <el-table-column label="期数" min-width="50">
                        <template slot-scope="scope">{{scope.row.NBRMTHS}}</template>
                    </el-table-column>
                    <el-table-column label="状态">
                        <template
                            slot-scope="scope"
                        >{{scope.row.STATUS | filterSTATUS(mpappstatusList)}}</template>
                    </el-table-column>
                    <el-table-column label="申请来源">
                        <template slot-scope="scope">{{scope.row.INPSRC | filterMPTYPE(mpsrcList)}}</template>
                    </el-table-column>
                    <el-table-column label="授权日期">
                        <template slot-scope="scope">{{scope.row.AUTHDAY}}</template>
                    </el-table-column>
                    <el-table-column label="请款日期">
                        <template slot-scope="scope">{{scope.row.MATCHDAY}}</template>
                    </el-table-column>
                    <el-table-column label="商户编号">
                        <template slot-scope="scope">{{scope.row.MERCHANT}}</template>
                    </el-table-column>
                </el-table>
                <div class="footer">
                    <el-button
                        type="primary"
                        size="small"
                        @click="handleChangePage('pre')"
                        :disabled="currentPageIndex <= 0"
                    >上一页</el-button>
                    <el-button
                        type="primary"
                        size="small"
                        @click="handleChangePage('next')"
                        :disabled="!nextButtonFlag"
                    >下一页</el-button>
                </div>
            </template>
        </cardComponent>
    </div>
</template>

<script>
import moment from 'moment';
import { mapState } from 'vuex';
import { trimString, getDictSelectList } from '@/utils/Common';
import { LOANSTATUS_DAILYBASIS } from '@/utils/Contants';
import cardComponent from '@/components/cardComponent/cardComponent.vue';

export default {
    name: 'mptransrecordqry',
    components: {
        cardComponent,
    },
    data() {
        return {
            pageLoading: false, // 页面loading
            nextButtonFlag: false, // 下翻页按钮 显示控制阀

            searchForm: { // 搜索表单字段
                accttype: '',//账户类型
                cardno: '',//卡号
                mpType: '', // 分期类型
                status: '', // 分期申请状态
            },
            mptypeList: [],
            mpappstatusList: [],
            mpsrcList: [],
            tableData: [],
            rules: { // 表单校验规则

            },
            cardList: [],
            currentSelectRow: '', //
            currentRowData: '', // 当前选择行的数据
            trialData: {}, // 试算结果数据
            isShowTrialDialog: false, // 试算结果展示弹框
            pagingDataList: [], // 翻页上送字段列表
            currentPageIndex: 0, // 当前页
        };
    },

    created() { },

    // 取缓存信息
    computed: mapState({
        cardInfo_3004: state => state.common.cardInfo_3004, // 默认卡信息
        defaultParams: state => state.common.defaultParams, // 接口默认参数
        pinFlag: state => state.common.pinFlag, // 是否密码检查标志
        AccountionTYPE_INFO: state => state.common.AccountionTYPE_INFO, //账户类别列表
        cardList_3601: state => state.common.cardList_3601, //卡列表
    }),

    filters: {
        // 状态 转译
        getStatusText(val) {
            let text = '';
            LOANSTATUS_DAILYBASIS.forEach((item) => {
                if (item.value === trimString(val)) {
                    text = item.label;
                }
            });
            return text;
        },

        // 格式化金额
        getFormatAmt(val) {
            let card4end = ''
            card4end = val.trim()
            card4end = card4end.substring(card4end.length - 4)
            return card4end
        },
        // 日期格式化
        getDateFormat(val) {
            if (val) {
                return moment(`${val}`).format('YYYY-MM-DD');
            }
            return '--';
        },
        filterSTATUS: (value, mpappstatusList) => {
            value = (`${value}`).trim();
            for (let index = 0; index < mpappstatusList.length; index++) {
                const element = mpappstatusList[index];
                if (element.code === value) {
                    return element.label;
                }
            }
        },
        filterMPTYPE: (value, mpsrcList) => {
            value = (`${value}`).trim();
            for (let index = 0; index < mpsrcList.length; index++) {
                const element = mpsrcList[index];
                if (element.code === value) {
                    return element.label;
                }
            }
        },
    },
    async mounted() {
        this.mptypeList = await getDictSelectList('MP_TYPE', this);
        this.mpappstatusList = await getDictSelectList('MP_APP_STATUS', this);
        this.mpsrcList = await getDictSelectList('MP_APP_SRC', this);
        this.init();
        this.changeCardList(this.cardInfo_3004.CATEGORY + '');
    },
    methods: {
        init() {
            console.log("默认账户类别：" + this.cardInfo_3004.CATEGORY);
            console.log("默认账户：" + this.cardInfo_3004.CARDNO);
            this.searchForm.accttype = this.cardInfo_3004.CATEGORY + '';

            //this.searchForm.cardno = this.cardInfo_3004.CARDNO;
        },
        changeCardList(val) {
            console.log("当前账户类型：" + val);
            let hasDefault = false; //是否包含默认卡
            this.cardList = [];
            this.cardList_3601.forEach((item) => {
                if (item.CATEGORY + '' === val) {
                    this.cardList.push(item);
                    if (item.CARDNBR === this.cardInfo_3004.CARDNO) {
                        hasDefault = true;
                    }
                }
            });

            //包含默认卡，卡号显示默认卡，不包含，显示cardList里第一张卡号
            if (hasDefault) {
                this.searchForm.cardno = this.cardInfo_3004.CARDNO;
            } else {
                this.searchForm.cardno = this.cardList[0].CARDNBR;
            }


        },
        // 点击查询 获取初始化列表数据
        handleGetListData(type) {
            console.log("type:" + type);
            this.$refs.searchForm.validate((valid) => {
                if (valid) {
                    this.pageLoading = true;
                    // 设置请求参数 -- 3046 交易
                    let APPREF = 0;
                    if (type != 'first') {
                        if (this.pagingDataList.length) { // 判断翻页上传字段取值

                            APPREF = this.pagingDataList[this.currentPageIndex].APPREF;
                        }
                    } else {
                        this.currentPageIndex = 0;
                        this.pagingDataList = [];
                    }


                    const appBody = {
                        OPT: 1, // 查询方式 1-用卡号查询 2-用证件号码查询
                        CARDNBR: this.searchForm.cardno, // 卡号
                        MPTYPE: this.searchForm.mpType, // 分期类型
                        STATUS: this.searchForm.status, // 分期申请状态
                        PINFLAG: this.pinFlag, // 是否检查密码标志 0-不检查
                        RTNIND: this.pagingDataList.length === 0 ? '' : 1, // 翻页标志 首次传空， 翻页传1
                        APPREF: APPREF, // 分期申请编号，首次查询时送空， 下翻页查询时上送上次查询结果的最后一条记录返回的分期付款申请编号
                    };
                    const params = JSON.parse(JSON.stringify(this.defaultParams));
                    // console.log(this.defaultParams, 'this.defaultParams')
                    params.body.appHead.tranCode = '3046';
                    params.body.appBody = appBody;

                    // 跑 3077 交易
                    this.$post.common.transPort(params).then((res) => {
                        this.pageLoading = false;
                        if (res.status === 200) {
                            const result = JSON.parse(res.data.jsonRes);
                            console.log(result, '响应数据 -- 3046');
                            if (result.sysHead.rspCd === '000000') {
                                this.tableData = result.body.appBody.dataList || [];

                                const currentPagingData = {
                                    APPREF: result.body.appBody.dataList[result.body.appBody.dataList.length - 1].APPREF,

                                };
                                this.nextButtonFlag = !(result.body.appBody.RTNIND === '0');
                                let flag = false;
                                let currentIndex;
                                this.pagingDataList.forEach((item, index) => { // 判断此次查询数据最后一条记翻页分期付款序号是否在已有列表中
                                    if (item.APPREF === currentPagingData.APPREF) {
                                        flag = true;
                                        currentIndex = index;
                                    }
                                });
                                if (flag) { // 存在
                                    this.currentPageIndex = currentIndex;
                                } else {
                                    this.pagingDataList.push(currentPagingData);
                                    this.currentPageIndex = this.pagingDataList.length - 1;
                                }
                            } else {

                                this.tableData = [];
                                this.currentPageIndex = 0;
                                this.pagingDataList = [];
                                this.nextButtonFlag = false;
                                const errorMsg = `错误代码：${result.sysHead.rspCd}, 错误信息：${result.sysHead.rspMsg}`;
                                this.$alert(errorMsg, '提示', {
                                    customClass: 'error', type: 'error',
                                });
                                this.nextButtonFlag = false;
                            }
                        } else {
                            this.$alert('请求失败!', '提示', {
                                customClass: 'error', type: 'error',
                            });
                        }
                    });
                } else {
                    this.pageLoading = false;
                }
            });
        },

        // 点击重置搜索表单
        handleReset() {
            this.$refs.searchForm.resetFields();
            // 清空当前选择行数据
            this.currentRowData = '';
            // 清空缓存翻页数据
            this.pagingDataList = [];
            // this.handleGetListData()
        },

        handleChange(row) {
            // console.log(this.$refs[row.MPNO], 'this.$refs[row.MPNO]')
            // this.$refs[row.MPNO].getElementsByTagName('input').blur()

            this.handleSelectRow(row);
        },

        // 选择表格行
        handleSelectRow(row) {
            // console.log(row, '第' + row.MPNO + '行数据')
            // if (row.MPNO === this.currentSelectRow) {
            //     this.currentSelectRow = ''
            //     this.currentRowData = ''
            // } else {
            // }
            this.currentSelectRow = row.MPNO;
            this.currentRowData = row;
        },

        // 上下页切换
        handleChangePage(type) {
            // 翻页之前先清空 当前选择行数据
            this.currentRowData = '';
            if (type === 'pre') { // 切换到上一页
                if (this.currentPageIndex - 2 < 0) {
                    this.pagingDataList = []; // 清空缓存 申请编号 -> 相当于首次查询
                } else {
                    this.currentPageIndex = this.currentPageIndex - 2;
                }
                this.handleGetListData(type);
            } else { // 切换到下一页
                this.handleGetListData(type);
            }
        },

        // 关闭对话框
        handleCloseDialog() {
            this.isShowTrialDialog = false;
        },
    },
};
</script>
<style rel="stylesheet/scss" lang="scss">
.mptransrecordqry {
    min-height: 100%;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;

    .mine .el-table {
        .el-radio {
            .el-radio__label {
                display: none;
                padding-left: 2px;
            }
        }
    }

    .searchForm {
        .el-form-item__content {
            display: inline-block;

            .el-select,
            .el-date-editor {
                /* max-width: 200px; */
            }
        }
    }
}
</style>
<style scoped lang="scss">
.mptransrecordqry {
    .buttonBox {
        margin: 30px 0;
        text-align: right;
    }

    .footer {
        text-align: center;
        margin-top: 30px;
    }
}

.trialDialog {
    .el-row {
        margin-bottom: 30px;

        .infoItem {
            .title {
                font-weight: 600;
                padding-right: 10px;
            }

            .info {
                color: #999;
            }
        }
    }
}
</style>
